<?php
//$Id: controller.php 9 2009-04-26 06:35:12Z bole.Chen $
uses('object','view');

class Controller extends Object {

    var $model;
    var $view;
    var $session;
    var $cookie;

    var $_var;

    var $pagesize = 12;

    //是否ajax请求
    var $ajax;
    var $ajaxFun;

    var $regexp;

    function __construct() {
        if (PHP_VERSION >= 5) parent::Object();

        //loopo.cn -> www.loopo.cn
        if ($_SERVER['HTTP_HOST'] && !preg_match('/^www\./', $_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] != 'localhost') {
            header("HTTP/1.1 301 Moved Permanently");
            header("Location: http://www.".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
            exit;
        }

        $this->regexp['username'] = '/^[\w'.chr(0x80).'-'.chr(0xff).']'.'{3,30}$/';
        $this->regexp['email'] = '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/';

        $this->session  =& $_SESSION;
        $this->cookie   =& $_COOKIE;
        if (!$this->session['sid']) $this->session['sid'] = session_id();

        //AutoLogin
        if (!$this->session['login'] && $this->cookie['autologin'] && $this->cookie['username'] && $this->cookie['password'] && !preg_match('/login\.php/i', $_SERVER['REQUEST_URI'])) {
            $this->redirect('/login.php?from='.urlencode(preg_replace('/from=[^&]+/', '', $_SERVER['REQUEST_URI'])));
        }

        $ctl = preg_replace('/Controller$/i', '', $this->toString());
        $this->view =& new View;

        if ($this->request['cpaint_function']) $this->_buildAjaxBackend($this->request['cpaint_function']);

        //Model
        //if ($this->ajax) $ctl = 'ajax'.$ctl;
        $modelfile = ROOT.'models'.DS.$ctl.'.php';
        if (file_exists($modelfile)) {
            require_once $modelfile;
            $ctl.='Model';
            if (!class_exists("$ctl")) die("<b>miss model class:</b> $ctl");
            $this->model =& new $ctl;
        } else {
            //die("<b>miss model file:</b> $modelfile");
        }
    }

    function __destruct() {
    }

    function &getView() {
        global $lp_action;

        if ($this->ajax) $this->ajaxClose();

        global $RUNTIME, $CountQueries, $CountCachedQueries;
        $RUNTIME['END'] = getmicrotime();

        $methods = array_unique(func_get_args());
        if (count($methods) == 0) $methods[0] = 'index';

        foreach ($methods as $method) {
            if (!method_exists($this, $method)) die('<b>miss Controller method:</b> '.$this->toString().'::'.$method);
            $this->view->set_vars($this->$method());

            $ctl = preg_replace('/controller$/', '', $this->toString());

            //For Plugin
            //print_r($lp_action);
            /*
            if (is_array( $lp_action[$ctl][$method] )) foreach ($lp_action[$ctl][$method] as $v) {
                call_user_func_array($v, array(&$this));
            }
            */
            //echo "{$ctl}::{$method}";
            do_action("{$ctl}::{$method}", &$this);
        }

        $this->view->set('RUNTIME', round($RUNTIME['END']-$RUNTIME['START'], 5));
        $this->view->set('QUERIES', (int)$CountQueries); //查询数据库次数
        $this->view->set('QUERIES_C', (int)$CountCachedQueries); //缓冲查询次数

        //Form 提交标志
        if ($this->post) $this->view->set('submit', true);
        if ($this->session) $this->view->set('session', $this->session);
        if ($this->cookie) $this->view->set('cookie', $this->cookie);
        if ($this->cookie) $this->view->set('CFG', $this->cfg);
        return $this->view;
    }

    function redirect($url) {
        if ($this->request['fromurl']) $url = ($this->request['fromurl']);
        @header('location:'.$url);
        exit;
    }

    //登录检测
    function needLogin() {
        if (!$this->session['login']) $this->redirect("/login.php?needlogin=1&from=" . urlencode(preg_replace('/from=[^&]+/', '', $_SERVER['REQUEST_URI'])));
    }

    function needAdmin() {
        if (!$this->session['admin']) die(header("location:/404.php"));
    }

    function clearSearchStr($str) {
        return preg_replace('/["\'\*\?_%]/', '', trim($str));
    }

    function ajaxClose() {
        if (is_array($this->ajaxFun)) foreach ($this->ajaxFun as $fun) $this->ajax->register( array(&$this, $fun) );
        $this->ajax->start();
        $this->ajax->return_data();
        exit;
    }

    function _buildAjaxBackend($fun) {
        uses('cpaint');
        $this->ajax = new cpaint_obj;
        $this->ajaxFun[] = trim($fun);
    }
}
?>
